home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / aptdaemon / console.py < prev    next >
Text File  |  2009-10-14  |  17KB  |  395 lines

  1. """
  2. This module provides a command line client for the aptdaemon
  3. """
  4. # Copyright (C) 2008-2009 Sebastian Heinlein <sevel@glatzor.de>
  5. #
  6. # Licensed under the GNU General Public License Version 2
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  21.  
  22. __author__ = "Sebastian Heinlein <devel@glatzor.de>"
  23.  
  24. import array
  25. import fcntl
  26. from gettext import gettext as _
  27. from optparse import OptionParser
  28. import os
  29. import pty
  30. import termios
  31. import time
  32. import tty
  33. import signal
  34. import sys
  35.  
  36. from aptsources.sourceslist import SourceEntry
  37. import apt_pkg
  38. import gobject
  39. import dbus.glib
  40.  
  41. import aptdaemon
  42. import client
  43. import enums
  44. import policykit1
  45.  
  46. ANSI_BOLD = chr(27) + "[1m"
  47. ANSI_RESET = chr(27) + "[0m"
  48.  
  49.  
  50. class ConsoleClient:
  51.     """
  52.     Command line interface client to aptdaemon
  53.     """
  54.     def __init__(self, show_terminal=True, allow_unauthenticated=False):
  55.         self._client = client.AptClient()
  56.         self.master_fd, self.slave_fd = pty.openpty()
  57.         self._signals = []
  58.         signal.signal(signal.SIGINT, self._on_cancel_signal)
  59.         signal.signal(signal.SIGQUIT, self._on_cancel_signal)
  60.         signal.signal(signal.SIGWINCH, self._on_terminal_resize)
  61.         self._terminal_width = self._get_terminal_width()
  62.         self._watchers = []
  63.         self._old_tty_mode = None
  64.         self._show_status = True
  65.         self._status = ""
  66.         self._percent = 0
  67.         self._show_terminal = show_terminal
  68.         self._allow_unauthenticated = allow_unauthenticated
  69.         self._show_progress = True
  70.         self._status_details = ""
  71.         self._progress_details = ""
  72.         # Used for a spinning line to indicate a still working transaction
  73.         self._spin_elements = "|/-\\"
  74.         self._spin_cur = -1
  75.         self._spin_stamp = time.time()
  76.         self._transaction = None
  77.  
  78.     def install_packages(self, packages):
  79.         """Install packages"""
  80.         trans = self._client.install_packages(packages,
  81.                                               exit_handler=self._on_exit)
  82.         self._run_transaction(trans)
  83.  
  84.     def add_repository(self, line="", sourcesfile=""):
  85.         """Add repository to the sources list."""
  86.         entry = SourceEntry(line)
  87.         return self._client.add_repository(entry.type, entry.uri, entry.dist,
  88.                                            entry.comps, entry.comment,
  89.                                            sourcesfile)
  90.  
  91.     def add_vendor_key_from_file(self, path):
  92.         """Install repository key file."""
  93.         trans = self._client.add_vendor_key_from_file(path,
  94.                                                      exit_handler=self._on_exit)
  95.         self._run_transaction(trans)
  96.  
  97.     def remove_vendor_key(self, fingerprint):
  98.         """Remove repository key."""
  99.         trans = self._client.remove_vendor_key(fingerprint,
  100.                                                exit_handler=self._on_exit)
  101.         self._run_transaction(trans)
  102.  
  103.     def install_file(self, path):
  104.         """Install package file."""
  105.         trans = self._client.install_file(path, exit_handler=self._on_exit)
  106.         self._run_transaction(trans)
  107.  
  108.     def list_trusted_vendor_keys(self):
  109.         """List the keys of the trusted vendors."""
  110.         keys = self._client.get_trusted_vendor_keys()
  111.         for key in keys:
  112.             print key
  113.  
  114.     def remove_packages(self, packages):
  115.         """Remove packages"""
  116.         trans = self._client.remove_packages(packages,
  117.                                              exit_handler=self._on_exit)
  118.         self._run_transaction(trans)
  119.  
  120.     def commit_packages(self, install, reinstall, remove, purge, upgrade):
  121.         """Commit changes"""
  122.         trans = self._client.commit_packages(install, reinstall, remove,
  123.                                              purge, upgrade,
  124.                                              exit_handler=self._on_exit)
  125.         self._run_transaction(trans)
  126.  
  127.     def update_cache(self):
  128.         """Update cache"""
  129.         trans = self._client.update_cache(exit_handler=self._on_exit)
  130.         self._run_transaction(trans)
  131.  
  132.     def upgrade_system(self):
  133.         """Upgrade system"""
  134.         trans = self._client.upgrade_system(exit_handler=self._on_exit)
  135.         self._run_transaction(trans)
  136.  
  137.     def _set_transaction(self, transaction):
  138.         """Monitor the given transaction"""
  139.         for handler in self._signals:
  140.             gobject.remove_source(handler)
  141.         self._transaction = transaction
  142.         self._signals = []
  143.         self._signals.append(
  144.             transaction.connect("allow-terminal", self._on_allow_terminal))
  145.         self._signals.append(
  146.             transaction.connect("status", self._on_status))
  147.         self._signals.append(
  148.             transaction.connect("status-details", self._on_status_details))
  149.         self._signals.append(
  150.             transaction.connect("progress", self._on_progress))
  151.         self._signals.append(
  152.             transaction.connect("progress-details", self._on_progress_details))
  153.         if self._show_terminal:
  154.             transaction.set_terminal(os.ttyname(self.slave_fd))
  155.         transaction.set_allow_unauthenticated(self._allow_unauthenticated)
  156.  
  157.     def _on_exit(self, trans, enum):
  158.         """Callback for the exit state of the transaction"""
  159.         # Make sure to dettach the terminal
  160.         self._detach()
  161.         if self._show_progress:
  162.             sys.stderr.write("[+] 100% " + ANSI_BOLD +
  163.                              "%-*.*s" % (self._terminal_width - 9,
  164.                                          self._terminal_width - 9,
  165.                                          enums.get_exit_string_from_enum(enum)) +
  166.                              ANSI_RESET + "\n")
  167.  
  168.         if enum == enums.EXIT_FAILED:
  169.             excep = trans.get_error()
  170.             msg = "%s: %s\n%s\n\n%s" % (
  171.                    _("ERROR"),
  172.                    enums.get_error_string_from_enum(excep.code),
  173.                    enums.get_error_description_from_enum(excep.code),
  174.                    excep.details)
  175.             print msg
  176.  
  177.     def _on_allow_terminal(self, transaction, allow_terminal):
  178.         """Callback for the AllowTerminal signal of the transaction"""
  179.         if self._show_terminal and allow_terminal == True and \
  180.            not self._watchers:
  181.             self._clear_progress()
  182.             self._show_progress = False
  183.             self._attach()
  184.         elif allow_terminal == False:
  185.             self._show_progress = True
  186.             self._detach()
  187.  
  188.     def _on_status(self, transaction, status):
  189.         """Callback for the Status signal of the transaction"""
  190.         self._status = enums.get_status_string_from_enum(status)
  191.         self._update_progress()
  192.  
  193.     def _on_status_details(self, transaction, text):
  194.         """Callback for the StatusDetails signal of the transaction."""
  195.         self._status_details = text
  196.         self._update_progress()
  197.  
  198.     def _on_progress_details(self, transaction, items_done, items_total,
  199.                              bytes_done, bytes_total, speed, eta):
  200.         """Callback for the ProgressDetails signal of the transaction."""
  201.         if bytes_total and speed:
  202.             self._progress_details = (_("Downloaded %sB of %sB at %sB/s") % \
  203.                                       (apt_pkg.SizeToStr(bytes_done),
  204.                                        apt_pkg.SizeToStr(bytes_total),
  205.                                        apt_pkg.SizeToStr(speed)))
  206.         elif bytes_total:
  207.             self._progress_details = (_("Downloaded %sB of %sB") % \
  208.                                       (apt_pkg.SizeToStr(bytes_done),
  209.                                        apt_pkg.SizeToStr(bytes_total)))
  210.         else:
  211.             self._progress_details = ""
  212.         self._update_progress()
  213.  
  214.     def _on_progress(self, transaction, percent):
  215.         """Callback for the Progress signal of the transaction"""
  216.         self._percent = percent
  217.         self._update_progress()
  218.  
  219.     def _update_progress(self):
  220.         """Update the progress bar."""
  221.         if not self._show_progress:
  222.             return
  223.         text = ANSI_BOLD + self._status + ANSI_RESET
  224.         if self._status_details:
  225.             text += " " + self._status_details
  226.         if self._progress_details:
  227.             text += " (%s)" % self._progress_details
  228.         text_width = self._terminal_width - 9
  229.         # Spin the progress line (maximum 5 times a second)
  230.         if self._spin_stamp + 0.2 < time.time():
  231.             self._spin_cur = (self._spin_cur + 1) % len(self._spin_elements)
  232.             self._spin_stamp = time.time()
  233.         spinner = self._spin_elements[self._spin_cur]
  234.         # Show progress information if available
  235.         if self._percent > 100:
  236.             percent = "---"
  237.         else:
  238.             percent = self._percent
  239.         sys.stderr.write("[%s] " % spinner +
  240.                          "%3.3s%% " % percent +
  241.                          "%-*.*s" % (text_width, text_width, text) + "\r")
  242.  
  243.     def _clear_progress(self):
  244.         """Clear progress information on stderr."""
  245.         sys.stderr.write("%-*.*s\r" % (self._terminal_width,
  246.                                        self._terminal_width,
  247.                                        " "))
  248.  
  249.     def _on_cancel_signal(self, signum, frame):
  250.         """Callback for a cancel signal."""
  251.         if self._transaction:
  252.             self._transaction.cancel()
  253.  
  254.     def _on_terminal_resize(self, signum, frame):
  255.         """Callback for a changed terminal size."""
  256.         self._terminal_width = self._get_terminal_width()
  257.         self._update_progress()
  258.  
  259.     def _detach(self):
  260.         """Dettach the controlling terminal to aptdaemon."""
  261.         for wid in self._watchers:
  262.             gobject.source_remove(wid)
  263.         if self._old_tty_mode:
  264.             tty.tcsetattr(pty.STDIN_FILENO, tty.TCSAFLUSH,
  265.                           self._old_tty_mode)
  266.  
  267.     def _attach(self):
  268.         """Attach the controlling terminal to aptdaemon. Based on pty.spwan()"""
  269.         try:
  270.             self._old_tty_mode = tty.tcgetattr(pty.STDIN_FILENO)
  271.             tty.setraw(pty.STDIN_FILENO)
  272.         except tty.error:    # This is the same as termios.error
  273.             self._old_tty_mode = None
  274.         flags = gobject.IO_IN | gobject.IO_ERR | gobject.IO_HUP
  275.         wid = gobject.io_add_watch(pty.STDIN_FILENO, flags,
  276.                                    self._copy_io, self.master_fd)
  277.         self._watchers.append(wid)
  278.         wid = gobject.io_add_watch(self.master_fd, flags,
  279.                                    self._copy_io, pty.STDOUT_FILENO)
  280.         self._watchers.append(wid)
  281.  
  282.     def _copy_io(self, source, condition, target):
  283.         """Callback to copy data between terminals."""
  284.         if condition == gobject.IO_IN:
  285.             data = os.read(source, 1024)
  286.             if target:
  287.                 os.write(target, data)
  288.             return True
  289.         os.close(source)
  290.         return False
  291.  
  292.     def _get_terminal_width(self):
  293.         """Return the witdh in characters of the current terminal."""
  294.         width = array.array("h", fcntl.ioctl(sys.stderr, termios.TIOCGWINSZ,
  295.                                              "\0" * 8))[1]
  296.         return width
  297.  
  298.     def _run_transaction(self, trans):
  299.         """Run the given transaction in blocking mode and catch authorization
  300.            errors."""
  301.         self._set_transaction(trans)
  302.         try:
  303.             trans.run(block=True)
  304.         except dbus.exceptions.DBusException, error:
  305.             if error.get_dbus_name() == \
  306.                "org.freedesktop.PolicyKit.Error.NotAuthorized":
  307.                 #FIXME: Improve wording
  308.                 msg = "%s: %s\n\n%s" % (_("ERROR"),
  309.                                         _("You are not authorized"),
  310.                                         error.get_dbus_message())
  311.                 print msg
  312.             else:
  313.                 raise error
  314.  
  315.  
  316. def main():
  317.     """Run a command line client for aptdaemon"""
  318.     epilog = _("To operate on more than one package put the package "
  319.                "names in quotation marks:\naptdcon --install \"foo bar\"")
  320.     parser = OptionParser(version=aptdaemon.__version__, epilog=epilog)
  321.     parser.add_option("-c", "--refresh", default="",
  322.                       action="store_true", dest="refresh",
  323.                       help=_("Refresh the cache"))
  324.     parser.add_option("-i", "--install", default="",
  325.                       action="store", type="string", dest="install",
  326.                       help=_("Install the given packages"))
  327.     parser.add_option("", "--reinstall", default="",
  328.                       action="store", type="string", dest="reinstall",
  329.                       help=_("Reinstall the given packages"))
  330.     parser.add_option("-r", "--remove", default="",
  331.                       action="store", type="string", dest="remove",
  332.                       help=_("Remove the given packages"))
  333.     parser.add_option("-p", "--purge", default="",
  334.                       action="store", type="string", dest="purge",
  335.                       help=_("Remove the given packages including "
  336.                              "configuration files"))
  337.     parser.add_option("-u", "--upgrade", default="",
  338.                       action="store", type="string", dest="upgrade",
  339.                       help=_("Install the given packages"))
  340.     parser.add_option("", "--upgrade-system", default="",
  341.                       action="store_true", dest="dist_upgrade",
  342.                       help=_("Upgrade the system"))
  343.     parser.add_option("", "--add-vendor-key", default="",
  344.                       action="store", type="string", dest="add_vendor_key",
  345.                       help=_("Add the vendor to the trusted ones"))
  346.     parser.add_option("", "--add-repository", default="", 
  347.                       action="store", type="string", dest="add_repository",
  348.                       help=_("Add new repository from the given deb-line"))
  349.     parser.add_option("", "--sources-file", action="store", default="",
  350.                       type="string", dest="sources_file",
  351.                       help=_("Specify an alternative sources.list.d file to "
  352.                              "which repositories should be added."))
  353.     parser.add_option("", "--list-trusted-vendors", default="",
  354.                       action="store_true", dest="list_trusted_vendor_keys",
  355.                       help=_("List trusted vendor keys"))
  356.     parser.add_option("", "--remove-vendor-key", default="",
  357.                       action="store", type="string", dest="remove_vendor_key",
  358.                       help=_("Remove the trusted key of the given fingerprint"))
  359.     parser.add_option("", "--hide-terminal",
  360.                       action="store_true", dest="hide_terminal",
  361.                       help=_("Do not attach to the apt terminal"))
  362.     parser.add_option("", "--allow-unauthenticated",
  363.                       action="store_true", dest="allow_unauthenticated",
  364.                       default=False,
  365.                       help=_("Allow packages from unauthenticated sources"))
  366.     (options, args) = parser.parse_args()
  367.     client = ConsoleClient(show_terminal=not options.hide_terminal,
  368.                            allow_unauthenticated=options.allow_unauthenticated)
  369.     if options.dist_upgrade:
  370.         client.upgrade_system()
  371.     elif options.refresh:
  372.         client.update_cache()
  373.     elif options.install or options.reinstall or options.remove or \
  374.          options.purge or options.upgrade:
  375.         client.commit_packages(options.install.split(),
  376.                                options.reinstall.split(),
  377.                                options.remove.split(),
  378.                                options.purge.split(),
  379.                                options.upgrade.split())
  380.     elif options.add_repository:
  381.         client.add_repository(options.add_repository, options.sources_file)
  382.     elif options.add_vendor_key:
  383.         #FIXME: Should detect if from stdin or file
  384.         client.add_vendor_key_from_file(options.add_vendor_key)
  385.     elif options.remove_vendor_key:
  386.         client.remove_vendor_key(options.remove_vendor_key)
  387.     elif options.list_trusted_vendor_keys:
  388.         client.list_trusted_vendor_keys()
  389.     else:
  390.         parser.print_help()
  391.         sys.exit(1)
  392.  
  393. if __name__ == "__main__":
  394.     main()
  395.